package com.bajiao.service.store.impl;

import cn.hutool.core.util.ObjectUtil;
import com.bajiao.common.constant.CommonConstant;
import com.bajiao.common.constant._Whole;
import com.bajiao.common.exception.DataHandleException;
import com.bajiao.common.util.FastJsonHelper;
import com.bajiao.common.util.PasswordUtil;
import com.bajiao.common.util.RedisUtil;
import com.bajiao.common.util.oConvertUtils;
import com.bajiao.common.util.vans.RegexTool;
import com.bajiao.entity.store.Store;
import com.bajiao.entity.store.StoreUser;
import com.bajiao.mapper.store.StoreMapper;
import com.bajiao.mapper.store.StoreUserMapper;
import com.bajiao.service.store.StorePermissionService;
import com.bajiao.service.store.StoreUserService;
import com.bajiao.vo.store.StorePermissionResponse;
import com.bajiao.vo.store.StoreUserInfo;
import com.bajiao.vo.store.StoreUserResponse;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 商家账号
 * @Author: FanJq
 * @Date:   2024-12-24
 * @Version: V1.0
 */
@Service
public class StoreUserServiceImpl extends ServiceImpl<StoreUserMapper, StoreUser> implements StoreUserService {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private StorePermissionService permissionService;

    /**
     * @Description
     * 根据账号获取
     * @date 2024/12/26 9:55
     * @author FanJq
     * @param account
     * @return {@link StoreUser}
    */
    @Override
    public StoreUser getByAccount(String account) {
        StoreUser storeUser = super.lambdaQuery().eq(StoreUser::getAccount, account).one();
        return storeUser;
    }

    /**
     * @Description
     * 获取用户详细信息
     * @date 2024/12/26 10:07
     * @author FanJq
     * @param user
     * @return {@link StoreUserInfo}
    */
    @Override
    public StoreUserInfo getUserInfo(StoreUser user) {
        StoreUserInfo response = FastJsonHelper.beanToBean(user, StoreUserInfo.class);
        List<StorePermissionResponse> permissionList = permissionService.getPermissionList();
        response.setPermissionList(permissionList);
        response.getPermissionList().stream()
                .filter(p -> response.getPermission().contains(p.getCode()))
                .forEach(permission -> permission.setIsHas(_Whole.ONE));
        return response;
    }

    /**
     * @Description
     * 修改密码
     * @date 2024/12/26 10:36
     * @author FanJq
     * @param user
     * @param cipher
     * @return
    */
    @Override
    public void modifyCipher(StoreUser user, String cipher) {
        String salt = oConvertUtils.randomGen(8);
        user.setPassword(PasswordUtil.encrypt(cipher, "", salt));
        user.setSalt(salt);
        super.updateById(user);
        String redisKey = CommonConstant.SIGN_STORE_USER_ID + user.getId();
        if (redisUtil.hasKey(redisKey)) {
            long expire = redisUtil.getExpire(redisKey);
            redisUtil.set(redisKey, user, expire);
        }
    }

    /**
     * @Description
     * 验证权限
     * @date 2024/12/26 11:56
     * @author FanJq
     * @param permissions
     * @param permission
     * @return {@link Boolean}
    */
    @Override
    public Boolean verifyPermission(String permissions, String permission) {
        if (permissions.contains(permission)) {
            return Boolean.TRUE;
        }
        throw new DataHandleException("无权限");
    }

    /**
     * @Description
     * 获取店铺子账号列表
     * @date 2024/12/28 14:20
     * @author FanJq
     * @param storeId
     * @return {@link List< StoreUserResponse>}
    */
    @Override
    public List<StoreUserResponse> getStoreUserList(String storeId) {
        List<StoreUser> storeUserList = super.lambdaQuery()
                .eq(StoreUser::getStoreId, storeId)
                .eq(StoreUser::getType, _Whole.TWO)
                .list();
        List<StorePermissionResponse> permissionList = permissionService.getPermissionList();
        List<StoreUserResponse> responseList = storeUserList.stream().map(model -> {
            StoreUserResponse response = FastJsonHelper.beanToBean(model, StoreUserResponse.class);
            response.setPermissionStrList(Arrays.asList(model.getPermission().split(StringPool.COMMA)));
            response.setPermissionList(permissionList);
            response.getPermissionList().stream()
                    .filter(p -> model.getPermission().contains(p.getCode()))
                    .forEach(permission -> permission.setIsHas(_Whole.ONE));
            return response;
        }).collect(Collectors.toList());
        return responseList;
    }

    /**
     * @Description
     * 创建店铺用户
     * @date 2024/12/28 14:28
     * @author FanJq
     * @param storeId
     * @param account
     * @param password
     * @param type
     * @return
    */
    @Override
    public void create(String storeId, String account, String password, Integer type) {
        if (!RegexTool.mobileCheck(account))
            throw new DataHandleException("手机号格式错误");
        StoreUser storeUser = this.getByAccount(account);
        if (ObjectUtil.isNotNull(storeUser))
            throw new DataHandleException("手机号已注册");
        storeUser = new StoreUser();
        storeUser.setStoreId(storeId);
        storeUser.setType(type);
        storeUser.setAccount(account);
        String salt = oConvertUtils.randomGen(_Whole.EIGHT);
        String encrypt = PasswordUtil.encrypt(password, "", salt);
        storeUser.setPassword(encrypt);
        storeUser.setSalt(salt);
        if (type.intValue() == _Whole.ONE) {
            List<StorePermissionResponse> permissionList = permissionService.getPermissionList();
            List<String> codeList = permissionList.stream().map(StorePermissionResponse::getCode).collect(Collectors.toList());
            storeUser.setPermission(String.join(StringPool.COMMA, codeList));
        }
        super.save(storeUser);
    }

    /**
     * @Description
     * 修改账号权限
     * @date 2024/12/28 14:53
     * @author FanJq
     * @param storeId
     * @param id
     * @param permissions
     * @return
    */
    @Override
    public void modifyPermission(String storeId, String id, String permissions) {
        StoreUser storeUser = super.getById(id);
        if (ObjectUtil.isNull(storeUser))
            throw new DataHandleException("账号不存在");
        if (!storeId.equals(storeUser.getStoreId()))
            throw new DataHandleException("非本店铺账号，无权限操作");
        //@create by FanJq 2024/12/28 14:55 更新权限
        super.lambdaUpdate().set(StoreUser::getPermission, permissions).eq(StoreUser::getId, id).update();
    }

    /**
     * @Description
     * 管理后台列表
     * @date 2025/1/6 14:22
     * @author FanJq
     * @param storeId
     * @param keywords
     * @param account
     * @return {@link List< StoreUser>}
    */
    @Override
    public List<StoreUser> getAdminList(String storeId, String keywords, String account) {
        return super.baseMapper.getAdminList(storeId, keywords, account);
    }
}
